import {
    AfterViewInit,
    Component,
    EventEmitter,
    Injector,
    OnDestroy,
    OnInit,
    Output,
    Renderer2,
    ViewChild
} from '@angular/core';
import { ConfigModule } from 'src/app/config.module';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import { NzModalRef, NzModalService } from 'ng-zorro-antd/modal';
import { Subject, Subscription } from 'rxjs';
import { filter, takeUntil } from 'rxjs/operators';
import { RoleModel } from '../../../../../models/system/role.model';
import { ValidatorService } from '../../../../../common/validator.service';
import { DragDrop } from '@angular/cdk/drag-drop';
import { NgxPermissionsService } from 'ngx-permissions';
import { SystemMenuService } from '../../service/system-menu.service';
import { iconData } from '../../../../../common/IconData';
import { NzTreeNodeOptions } from 'ng-zorro-antd/core/tree/nz-tree-base-node';

@Component({
    selector: 'app-menu-option',
    templateUrl: './index.html',
    styleUrls: ['./index.scss'],
})
export class MenuOptionComponent implements OnInit, AfterViewInit, OnDestroy {
    @ViewChild('modalContent') modalContent: any;
    @ViewChild('modalFooter') modalFooter: any;
    @Output() getUserList: EventEmitter<any> = new EventEmitter<any>();
    modalLoadingState: boolean;
    saveLoadingState: boolean;
    roles: Array<RoleModel>;
    dataForm: FormGroup;
    router$: Subscription;
    onDestroy$: Subject<any> = new Subject<any>();
    searchObj = {
        pageNum: 1,
        pageSize: this._config.pageSize,
        name: '',
        phoneNumber: '',
        emailNumber: ''
    };
    loadingState: boolean;
    total: number;

    entity: any = {} as any;
    userId: string; //用户ID
    modalRef: NzModalRef; //用户操作弹窗
    menuTree: any;

    constructor(
        public _config: ConfigModule,
        private _formBuilder: FormBuilder,
        private _router: Router,
        private _activatedRoute: ActivatedRoute,
        private _nzModalService: NzModalService,
        private _validService: ValidatorService,
        private _renderer2: Renderer2,
        private _dragDrop: DragDrop,
        private _ngxPermissionsService: NgxPermissionsService,
        private _injector: Injector,
        private menuService: SystemMenuService
    ) {
        // 表单验证
        this.dataForm = this._formBuilder.group({
            parentId: [''],
            menuType: [''],
            icon: [''],
            menuName: ['',Validators.required],
            orderNum: ['',Validators.required],
            isFrame: [''],
            path: [''],
            visible: [''],
            status: [''],
            perms: [''],
            component: [''],
            isCache: [''],
            query: [''],

        });

        this.router$ = this._router.events
            .pipe(
                filter((ev) => ev instanceof NavigationEnd),
                takeUntil(this.onDestroy$)
            )
            .subscribe(() => {
                this.getUserList.emit();
            });
    }

    ngOnInit() {
    }

    ngAfterViewInit() {}

    ngOnDestroy() {
        this.onDestroy$.complete();
    }
    /**
     * 打开操作弹窗
     * @param id 用户ID
     * @param modalContent 弹窗模板内容
     * @param modalFooter 弹窗模板底部内容
     */
    onModalOpen(id: string) {
        this.getMenuTree();
        this.entity.userId = id;
        this.modalRef = this._nzModalService.create({
            nzTitle: id ? '编辑菜单' : '新增菜单',
            nzContent: this.modalContent,
            nzFooter: this.modalFooter,
            nzWidth: this._config.modalWidth,
            nzBodyStyle: this._config.modalContentHeight,
        });

        this.modalRef.afterOpen.subscribe(() => {
            const modalDragRef = this._renderer2.selectRootElement('.ant-modal-content', true);
            const modalDragHeaderRef = this._renderer2.selectRootElement('.ant-modal-header', true);

            const modalDrag = this._dragDrop.createDrag(modalDragRef);
            modalDrag.withHandles([modalDragHeaderRef]);
            modalDrag.withBoundaryElement(document.body);
        });

        this.modalRef.afterClose.subscribe(() => {
            this.dataForm.reset();
            for (const key of Object.keys(this.entity)) {
                delete this.entity[key];
            }
        });

        if (id) {
            this.modalLoadingState = true;
            this.menuService.get(id).subscribe((res) => {
                if (res.success) {
                    this.entity = res.data;
                }
            }).add(()=>{
                this.modalLoadingState = false;
            });
        }
    }


    /**
     * 保存用户
     */
    onSave() {
        if (this.entity.menuId) {
            this.menuService.update(this.entity).subscribe((res) => {
                if (res.success) {
                    this.modalRef.close();
                    this.dataForm.reset();
                    for (const key of Object.keys(this.entity)) {
                        delete this.entity[key];
                    }
                    this.getUserList.emit();
                }
            });
        } else {
            this.menuService.add(this.entity).subscribe((res) => {
                if (res.success) {
                    this.modalRef.close();
                    this.dataForm.reset();
                    for (const key of Object.keys(this.entity)) {
                        delete this.entity[key];
                    }
                    this.getUserList.emit();
                }
            });
        }
    }

    /**
     * 获取菜单树
     */
    getMenuTree() {
        this.menuService.list({}).subscribe(res=>{
            if (res.code === 200){
                let treeNode: any={} as NzTreeNodeOptions;
                treeNode.title = '主类目';
                treeNode.expanded = false;
                treeNode.key = 0;
                treeNode.children = this.convertListToTree(res.data,0);
                treeNode.isLeaf = false;
                let treeNodeList = [treeNode];
                this.menuTree = treeNodeList;
            }
        })
    }

    convertListToTree(data:any[],prentId:number): Array<NzTreeNodeOptions> {
        if (!data) return;
        let treeData: NzTreeNodeOptions[] = [];
        data.forEach(node => {
            if (node.parentId === prentId){
                let treeNode: NzTreeNodeOptions={} as NzTreeNodeOptions;
                treeNode.title = node.menuName;
                treeNode.expanded = false;
                treeNode.key = node.menuId;
                treeNode.children = this.convertListToTree(data, node.menuId);
                treeNode.isLeaf = treeNode.children.length == 0;
                treeData.push(treeNode);
            }
        })
        return treeData
    }


    /**
     * 图标选择表
     */
    menuTableVisible = false;
    menuTableVisibleChange($event: any) {
    }

    closeMenuTable() {
        this.menuTableVisible = false;
    }

    protected readonly iconData = iconData;

    iconSelect($event: any) {
        this.entity.icon = $event;
        this.closeMenuTable();
    }

    menuChange() {
        const pathControl = this.dataForm.get('path');
        if (this.entity.menuType === 'M' || this.entity.menuType === 'C') {
            const currentValidators = pathControl.validator ? [pathControl.validator] : [];
            if (!currentValidators.some(v => v({} as any).required)) {
                pathControl.setValidators([...currentValidators, Validators.required]);
            }
        } else {
            const currentValidators = pathControl.validator ? [pathControl.validator] : [];
            pathControl.setValidators(currentValidators.filter(v => !v({} as any).required));
        }
        pathControl.updateValueAndValidity();
    }
}
